package com.example.testone.utils

import java.nio.charset.Charset
import kotlin.experimental.and
import kotlin.experimental.xor

class ByteUtil {
    companion object{
        //字节签名
        fun sign(bytes: ByteArray):Byte {
            var byte:Byte = 0x00
            for (i in 0 until bytes.size){
                byte = (byte + bytes[i]).toByte()
            }
            return byte
        }


        /**
         * 字符串转化成为16进制字符串
         *
         * @param s
         * @return
         */
        fun strTo16(s: String): String {
            var str = ""
            for (i in 0 until s.length) {
                val ch = s[i].toInt() and (0xFF)
                val s4 = Integer.toHexString(ch)
                str = str + s4
            }
            return str
        }

        /**
         * 16进制转换成为string类型字符串
         *
         * @param s
         * @return
         */
        fun hexStringToString(s: String?): String? {
            var s = s
            if (s == null || s == "") {
                return null
            }
            s = s.replace(" ", "")
            val baKeyword = ByteArray(s.length / 2)
            for (i in baKeyword.indices) {
                try {
                    baKeyword[i] = (0xff and s.substring(i * 2, i * 2 + 2).toInt(16)).toByte()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            try {
                s = String(baKeyword, Charset.forName("UTF-8"))
                String()
            } catch (e1: Exception) {
                e1.printStackTrace()
            }
            return s
        }

        /**
         * 向串口发送数据转为字节数组
         */
        fun hex2byte(hex: String): ByteArray? {
            val digital = "0123456789ABCDEF"
            val hex1 = hex.replace(" ", "")
            val hex2char = hex1.toCharArray()
            val bytes = ByteArray(hex1.length / 2)
            var temp: Byte
            for (p in bytes.indices) {
                temp = (digital.indexOf(hex2char[2 * p]) * 16).toByte()
                temp = (temp +digital.indexOf(hex2char[2 * p + 1]).toByte()).toByte()
                bytes[p] = (temp and 0xff.toByte()) as Byte
            }
            return bytes
        }

        //单个转换
        fun toHexStr(byte: Byte):String{
            return with(StringBuilder()) {
                val hex = byte.toInt() and (0xFF)
                val hexStr = Integer.toHexString(hex)
                if (hexStr.length == 1) append("0").append(hexStr)
                else append(hexStr)
                toString()
            }
        }
        //数组转换
        fun toHexStr(byteArray: ByteArray):String{
            return with(StringBuilder()) {
                byteArray.forEach {
                    append(toHexStr(it))
                }
                toString()
            }
        }


        /**
         * 接收到的字节数组转换16进制字符串
         */
        fun bytes2HexString(b: ByteArray, size: Int): String {
            var ret = ""
            for (i in 0 until size) {
                var hex = Integer.toHexString((b[i] and 0xFF.toByte()).toInt())
                if (hex.length == 1) {
                    hex = "0$hex"
                }
                ret += hex.toUpperCase()
            }
            return ret
        }

        fun bytesToHexString(src: ByteArray?): String? {
            val stringBuilder = StringBuilder("")
            if (src == null || src.size <= 0) {
                return null
            }
            for (i in src.indices) {
                val v: Int = src[i].and(0xFF.toByte()).toInt()
                val hv = Integer.toHexString(v)
                if (hv.length < 2) {
                    stringBuilder.append(0)
                }
                stringBuilder.append(hv)
            }
            return stringBuilder.toString()
        }

        /**
         * 接收到的字节数组转换16进制字符串
         */
        fun byteToStr(b: ByteArray, size: Int): String {
            var ret = ""
            for (i in 0 until size) {
                var hex = Integer.toHexString((b[i] and 0xFF.toByte()).toInt())
                if (hex.length == 1) {
                    hex = "0$hex"
                }
                ret += hex.toUpperCase()
            }
            return ret
        }

//        /**
//         * 计算CRC16校验码
//         * 逐个求和
//         *
//         * @param bytes 字节数组
//         * @return [String] 校验码
//         * @since 1.0
//         */
//        fun getCRC_16(bytes: ByteArray): String? {
//            var CRC = 0x0000ffff
//            val POLYNOMIAL = 0x0000a001
//            var i: Int
//            var j: Int
//            i = 0
//            while (i < bytes.size) {
//                CRC = CRC xor (bytes[i].toInt() and 0x000000ff)
//                j = 0
//                while (j < 8) {
//                    if (CRC and 0x00000001 != 0) {
//                        CRC = CRC shr 1
//                        CRC = CRC xor POLYNOMIAL
//                    } else {
//                        CRC = CRC shr 1
//                    }
//                    j++
//                }
//                i++
//            }
//            if (Integer.toHexString(CRC).toUpperCase().length == 2) {
//                return byteToStr(bytes, bytes.size) + "00" + Integer.toHexString(CRC).toUpperCase()
//            } else if (Integer.toHexString(CRC).toUpperCase().length == 3) {
//                return byteToStr(bytes, bytes.size) + "0" + Integer.toHexString(CRC).toUpperCase()
//            }
//            return byteToStr(bytes, bytes.size) + Integer.toHexString(CRC).toUpperCase()
//        }
//
//        /**
//         * 指令校验和,并取出后两位字节
//         */
//        fun getSum16(msg: ByteArray, length: Int): String? {
//            var mSum: Long = 0
//            val mByte = ByteArray(length)
//            /** 逐Byte添加位数和  */
//            for (byteMsg in msg) {
//                val mNum = if (byteMsg.toLong() >= 0) byteMsg.toLong() else byteMsg.toLong() + 256
//                mSum += mNum
//            }
//            /** end of for (byte byteMsg : msg)  */
//            /** 位数和转化为Byte数组  */
//            for (liv_Count in 0 until length) {
//                mByte[length - liv_Count - 1] = (mSum shr liv_Count * 8 and 0xff).toByte()
//            }
//            /** end of for (int liv_Count = 0; liv_Count < length; liv_Count++)  */
//            return byteToStr(msg, length) + byteToStr(mByte, mByte.size).substring(
//                byteToStr(
//                    mByte,
//                    mByte.size
//                ).length - 4, byteToStr(mByte, mByte.size).length
//            )
//        }


//        /** 16进制的字符串转换成16进制字符串数组
//         * @param src
//         * @return
//         */
//        fun HexString2Bytes(src: String): ByteArray {
//            val len = src.length / 2
//            val ret = ByteArray(len)
//            val tmp = src.toByteArray()
//            for (i in 0 until len) {
//                ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1])
//            }
//            return ret
//        }
//
//
//        fun uniteBytes(src0: Byte, src1: Byte): Byte {
//            var _b0 = java.lang.Byte.decode("0x" + String(byteArrayOf(src0))).toByte()
//            _b0 = (_b0 shl 4) as Byte
//            shl()
//            val _b1 = java.lang.Byte.decode("0x" + String(byteArrayOf(src1))).toByte()
//            return (_b0 xor _b1) as Byte
//        }
    }
}